'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import {
  MessageSquare,
  Plus,
  Settings,
  FileText,
  Search,
  Menu,
  Trash2,
  Edit3,
} from 'lucide-react';
import {
  useCurrentSession,
  useSessions,
  useChatActions,
  useUIActions,
  useUser,
} from '@/store';
import { ChatSession } from '@/types';
import { cn } from '@/lib/utils';

interface SessionItemProps {
  session: ChatSession;
  isActive: boolean;
  onSelect: (session: ChatSession) => void;
  onDelete: (sessionId: string) => void;
  onRename: (sessionId: string, newTitle: string) => void;
}

function SessionItem({
  session,
  isActive,
  onSelect,
  onDelete,
  onRename,
}: SessionItemProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editTitle, setEditTitle] = useState(session.title);

  const handleRename = () => {
    if (editTitle.trim() && editTitle !== session.title) {
      onRename(session.id, editTitle.trim());
    }
    setIsEditing(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleRename();
    } else if (e.key === 'Escape') {
      setEditTitle(session.title);
      setIsEditing(false);
    }
  };

  return (
    <div
      className={cn(
        'group relative p-3 rounded-lg cursor-pointer transition-colors',
        isActive
          ? 'bg-primary/10 border border-primary/20'
          : 'hover:bg-muted/50'
      )}
    >
      <div onClick={() => onSelect(session)} className='flex-1'>
        {isEditing ? (
          <input
            type='text'
            value={editTitle}
            onChange={e => setEditTitle(e.target.value)}
            onBlur={handleRename}
            onKeyDown={handleKeyDown}
            className='w-full bg-transparent border-none outline-none text-sm font-medium'
            autoFocus
          />
        ) : (
          <div className='flex items-center justify-between'>
            <div className='flex-1 min-w-0'>
              <h3 className='text-sm font-medium truncate'>{session.title}</h3>
              <p className='text-xs text-muted-foreground mt-1'>
                {new Date(session.created_at).toLocaleDateString()}
              </p>
            </div>
            {session.message_count && (
              <Badge variant='secondary' className='ml-2 text-xs'>
                {session.message_count}
              </Badge>
            )}
          </div>
        )}
      </div>

      {/* 操作按钮 */}
      <div className='absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-1'>
        <Button
          variant='ghost'
          size='sm'
          className='h-6 w-6 p-0'
          onClick={e => {
            e.stopPropagation();
            setIsEditing(true);
          }}
        >
          <Edit3 className='h-3 w-3' />
        </Button>
        <Button
          variant='ghost'
          size='sm'
          className='h-6 w-6 p-0 text-destructive hover:text-destructive'
          onClick={e => {
            e.stopPropagation();
            onDelete(session.id);
          }}
        >
          <Trash2 className='h-3 w-3' />
        </Button>
      </div>
    </div>
  );
}

export function Sidebar() {
  const user = useUser();
  const currentSession = useCurrentSession();
  const sessions = useSessions();
  const {
    setCurrentSession,
    addSession,
    deleteSession,
    updateSession,
    setSessions,
  } = useChatActions();
  const { toggleSidebar } = useUIActions();
  const [isLoading, setIsLoading] = useState(false);

  // 加载会话列表
  useEffect(() => {
    if (user) {
      loadSessions();
    }
  }, [user]);

  const loadSessions = async () => {
    if (!user) return;

    setIsLoading(true);
    try {
      const response = await fetch(`/api/chat?userId=${user.id}`);
      const data = await response.json();

      if (data.success) {
        setSessions(data.data);
      }
    } catch (error) {
      console.error('加载会话失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleNewChat = () => {
    setCurrentSession(null);
  };

  const handleSelectSession = (session: ChatSession) => {
    setCurrentSession(session);
  };

  const handleDeleteSession = async (sessionId: string) => {
    try {
      const response = await fetch(`/api/chat/sessions/${sessionId}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        deleteSession(sessionId);
      }
    } catch (error) {
      console.error('删除会话失败:', error);
    }
  };

  const handleRenameSession = async (sessionId: string, newTitle: string) => {
    try {
      const response = await fetch(`/api/chat/sessions/${sessionId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ title: newTitle }),
      });

      if (response.ok) {
        updateSession(sessionId, { title: newTitle });
      }
    } catch (error) {
      console.error('重命名会话失败:', error);
    }
  };

  return (
    <div className='h-full bg-muted/30 border-r border-border flex flex-col'>
      {/* 头部 */}
      <div className='p-4 border-b border-border'>
        <div className='flex items-center justify-between mb-4'>
          <h1 className='text-lg font-semibold'>RAG Chat</h1>
          <Button
            variant='ghost'
            size='sm'
            onClick={toggleSidebar}
            className='h-8 w-8 p-0'
          >
            <Menu className='h-4 w-4' />
          </Button>
        </div>

        <Button
          onClick={handleNewChat}
          className='w-full justify-start gap-2'
          variant='default'
        >
          <Plus className='h-4 w-4' />
          新建对话
        </Button>
      </div>

      {/* 会话列表 */}
      <div className='flex-1 overflow-hidden'>
        <div className='p-4'>
          <div className='flex items-center gap-2 mb-3'>
            <MessageSquare className='h-4 w-4 text-muted-foreground' />
            <span className='text-sm font-medium text-muted-foreground'>
              对话历史
            </span>
          </div>

          <ScrollArea className='h-[calc(100vh-300px)]'>
            {isLoading ? (
              <div className='space-y-2'>
                {[...Array(3)].map((_, i) => (
                  <div
                    key={i}
                    className='h-16 bg-muted/50 rounded-lg animate-pulse'
                  />
                ))}
              </div>
            ) : sessions.length > 0 ? (
              <div className='space-y-2'>
                {sessions.map(session => (
                  <SessionItem
                    key={session.id}
                    session={session}
                    isActive={currentSession?.id === session.id}
                    onSelect={handleSelectSession}
                    onDelete={handleDeleteSession}
                    onRename={handleRenameSession}
                  />
                ))}
              </div>
            ) : (
              <div className='text-center text-muted-foreground text-sm py-8'>
                <MessageSquare className='h-8 w-8 mx-auto mb-2 opacity-50' />
                <p>暂无对话历史</p>
                <p className='text-xs mt-1'>开始新对话来创建历史记录</p>
              </div>
            )}
          </ScrollArea>
        </div>
      </div>

      {/* 底部导航 */}
      <div className='p-4 border-t border-border space-y-2'>
        <Button
          variant='ghost'
          className='w-full justify-start gap-2'
          size='sm'
        >
          <FileText className='h-4 w-4' />
          文档管理
        </Button>
        <Button
          variant='ghost'
          className='w-full justify-start gap-2'
          size='sm'
        >
          <Search className='h-4 w-4' />
          搜索
        </Button>
        <Button
          variant='ghost'
          className='w-full justify-start gap-2'
          size='sm'
        >
          <Settings className='h-4 w-4' />
          设置
        </Button>

        {user && (
          <div className='pt-2 border-t border-border'>
            <div className='flex items-center gap-2 px-2 py-1'>
              <div className='h-6 w-6 bg-primary rounded-full flex items-center justify-center text-xs text-primary-foreground font-medium'>
                {user.name.charAt(0).toUpperCase()}
              </div>
              <span className='text-sm text-muted-foreground truncate'>
                {user.name}
              </span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
